﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using System.Runtime.InteropServices;
using System.Text.RegularExpressions;
using System.Net.Mail;
using System.ComponentModel;

namespace Kiosk
{
    /// <summary>
    /// Interaction logic for PasswordPrompt.xaml
    /// </summary>
    public partial class PasswordPrompt : Window
    {

        [DllImport("user32.dll")]
        static extern bool HideCaret(IntPtr hWnd); //for caret hiding in makeshift password box
        OnScreenKeyboard theKeyboard = new OnScreenKeyboard();
        private string additionalComments;

        public Window previousWindow { get; set; }

        public PasswordPrompt()
        {
            InitializeComponent();

            MainGrid.Children.Add(theKeyboard);
            Grid.SetRow(theKeyboard, 2);
            Grid.SetColumn(theKeyboard, 0);
            Grid.SetColumnSpan(theKeyboard, 3);
            theKeyboard.VerticalAlignment = VerticalAlignment.Bottom;
            additionalComments = "";       
        }//end constructor PasswordPrompt

        public PasswordPrompt(string comments)
        {
            InitializeComponent();

            MainGrid.Children.Add(theKeyboard);
            Grid.SetRow(theKeyboard, 2);
            Grid.SetColumn(theKeyboard, 0);
            Grid.SetColumnSpan(theKeyboard, 3);
            theKeyboard.VerticalAlignment = VerticalAlignment.Bottom; 
            additionalComments = comments;
        }

        /// <summary>
        /// This method clears the password box and returns user to the previous page
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnCancel_Click(object sender, RoutedEventArgs e)
        {            
            previousWindow.Show();
            this.Close();            
        }//end method btnCancel_Click


        /// <summary>
        /// This method is called when the Submit button is clicked. It checks to see if the 
        /// password field has text. If it does then it then checks for SQL injection.
        /// If it passes all of this it will then check the credentials against the database.
        /// If the credentials are correct, the email is sent.
        /// </summary>
        /// <param name="sender"></param>
        /// <param name="e"></param>
        private void btnSubmit_Click(object sender, RoutedEventArgs e)
        {
            //Check for an empty password 
            if (txtPassword.Password == String.Empty || txtPassword.Password == null)
            {
                txtErrorMessage.Text = "The PASSWORD can not be blank.";
            }
            //Check the credentials against the database
            else
            {
                try
                {
                    if (sGlobals.isValidPassword(sGlobals.currentUsername, txtPassword.Password))
                    {
                        sendEmail();
                        string logStatement = "INSERT INTO lgd_mentor_student_actions (mentor_id, student_id, " +
                                        "date_time, action_performed_id) VALUES ('" + sGlobals.selectedMentorID + "' , (SELECT user_id FROM users " +
                                        "WHERE username = '" + sGlobals.currentUsername + "'), NOW(), 'E')";
                        try
                        {
                            sGlobals.dbWrapper.ExecuteNonQuery(logStatement);
                        }
                        catch (Exception ex)
                        {
                            Console.WriteLine("There was an error connecting to the database with exception {0}", ex.Message);
                        }
                        sGlobals.mentorDisplay.previousPage.Show();
                        foreach (Window win in Application.Current.Windows)
                        {
                            if ((string)win.Tag == "comments")
                            {
                                win.Close();
                            }
                        }
                        this.Close();
                    }
                    else
                    {
                        txtErrorMessage.Text = "The PASSWORD is not valid";
                    }
                }
                catch (Exception ex)
                {
                    if (!sGlobals.hasLogout)
                    {
                        WarningMessage warning = new WarningMessage();
                        warning.lblMessage.Content = "There was a problem submitting the email.\r\nIf the problem persists, please contact your system administrator";
                        warning.ShowDialog();

                        sGlobals.mentorDisplay.previousPage.Show();
                        foreach (Window win in Application.Current.Windows)
                        {
                            if ((string)win.Tag == "comments")
                            {
                                win.Close();
                            }
                        }
                        this.Close();
                    }
                }
            }
        }//end method btnSubmit_click

        private void focusHandler(object sender, RoutedEventArgs e)
        {
            if (sender is PasswordBox) //show keyboard and bind
            {
                theKeyboard.bindToControl((TextBox)sender);
                theKeyboard.show();
            }
            else if (sender is OnScreenKeyboard) // special do nothing case...focus is getting bounced around between the keyboard and bound control
            {

            }
            else //hide keyboard (clicked button or window or something)
            {
                theKeyboard.clearControlBinding();
                theKeyboard.hide();
            }
        }

        private void windowLeftMouseButtonUp(object sender, MouseButtonEventArgs e)
        {
            theKeyboard.clearControlBinding();
            theKeyboard.hide();
            btnSubmit.Focus();
        }

        private void sendEmail()
        {
            sGlobals.sendingEmail = true; 
            string mentorEmailQuery = "SELECT email FROM mentor WHERE mentor_id = '" + sGlobals.selectedMentorID + "'";
            string kioskEmailQuery = "SELECT setting_value FROM settings WHERE setting_name = 'EMAIL ADDRESS'";
            MailAddress from = new MailAddress(sGlobals.dbWrapper.ExecuteScalarSQL(kioskEmailQuery));
            MailAddress to = new MailAddress(sGlobals.dbWrapper.ExecuteScalarSQL(mentorEmailQuery));
            MailMessage message = new MailMessage(from, to);
            message.Subject = "Clearfield Career Kiosk";
            message.Body = sGlobals.contactMentor.emailText + additionalComments;
            sGlobals.smtpClient.SendCompleted += new SendCompletedEventHandler(sendCompleted);
            MessageBox sendingMessage = new MessageBox("Please wait while your email is being sent", "sending");
            try
            {
                sGlobals.smtpClient.SendAsync(message, "token");
                sendingMessage.ShowDialog();
            }
            catch (Exception e)
            {
                WarningMessage warn = new WarningMessage();
                warn.lblMessage.Content = "There was a problem sending the email. Please try again later.\r\nIf the problem continues, contact your system administrator.";
                warn.ShowDialog();
                sGlobals.sendingEmail = false;
            }                                        
        }

        private void sendCompleted(object sender, AsyncCompletedEventArgs e)
        {
            foreach (Window win in Application.Current.Windows)
            {
                if ((string)win.Tag == "sending")
                {
                    win.Close();
                }
            }
            if (e.Error != null)
            {
                WarningMessage warn = new WarningMessage();
                warn.lblMessage.Content = "There was a problem sending the email. Please try again later.\r\nIf the problem continues, please contact your system administrator.";
                warn.ShowDialog();
            }
            sGlobals.sendingEmail = false;
        }

        private void txtPassword_GotFocus(object sender, RoutedEventArgs e)
        {
            theKeyboard.bindToControl(sender);
            theKeyboard.show();
        }
    }//end partial class PasswordPrompt : Window
}//end namespace Kiosk
